package org.vnl.platform.spring.jpa.mvc;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.vnl.platform.impl.openjpa.std.EntityManagerContanier;

public class JPATransactionInterceptor implements HandlerInterceptor {
    
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        Collection<EntityManager> ems = EntityManagerContanier.getInstance().getCurrentEntityManagers();
        boolean rollback = false;
        for (EntityManager em : ems) {
            if (em.getTransaction().getRollbackOnly()) {
                rollback = true;
                break;
            }
        }
        if (rollback) {
            for (EntityManager em : ems) {
                em.getTransaction().rollback();
            }
        } else {
            for (EntityManager em : ems) {
                em.getTransaction().commit();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
        
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        return false;
    }

}
